import 'package:flutter/material.dart';

class DropDownMenu extends StatefulWidget {
  final List<dynamic> datas;
  final Map<String,String> keyItem;
  dynamic value;
  final Function onChange;
  final EdgeInsets margin;
  Border border;
  BorderRadiusGeometry  radius;
  final String hitText;
  DropDownMenu({
    Key key,
    this.datas,
    @required this.value,
    this.keyItem,
    this.onChange,
    this.hitText = "",
    this.border,
    this.radius,
    this.margin = const EdgeInsets.only(top: 8,bottom: 8)
  }):
  assert(datas != null);
  @override
  State<StatefulWidget> createState() {
    return _DropDownMenu();
  }
}

class _DropDownMenu extends State<DropDownMenu>{

  //设置DropdownMenuItem Widget
  List<DropdownMenuItem> getMenuItems(){
    List<DropdownMenuItem> menuItems=List();
    for(int i=0;i<widget.datas.length;i++){
      if(widget.keyItem != null && widget.keyItem.keys.toList().length == 1){
        String key=widget.keyItem.keys.toList()[0];
        String val=widget.keyItem.values.toList()[0];
        menuItems.add(new DropdownMenuItem(
          child:Text(widget.datas[i][val]),
          value: widget.datas[i][key],
        ));
      }else{
        menuItems.add(new DropdownMenuItem(
          child:Text(widget.datas[i]),
          value: widget.datas[i],
        ));
      }
    }
    return menuItems;
  }

  //获取下标index和Value
  Map<String,dynamic> getItemData(selectValue){
      var index,value,item;
      value = selectValue;
      if(widget.keyItem == null){
        index=widget.datas.indexOf(value);
        item = value;
      }else{
        String val=widget.keyItem.keys.toList()[0];
        for(int i=0;i<widget.datas.length;i++){
          if(value == widget.datas[i][val]){
            index=i;
            item = widget.datas[i];
            break;
          }
        }
      }
    return {"index":index,"value":value,"item":item};
  }

  @override
  Widget build(BuildContext context) {
    if(widget.border==null){
      widget.border=Border.all(color: Color(0xFFCCCCCC),width:0.5);
    }
    if(widget.radius==null){
      widget.radius=BorderRadius.circular(10);
    }
    if(widget.datas.isEmpty){
      return Container();
    }
    // TODO: implement build
    return Container(
      margin: widget.margin,
      padding: EdgeInsets.only(left:12,right: 18),
      decoration: BoxDecoration(
        color: Colors.white,
        border: widget.border,
        borderRadius: widget.radius
      ),
      child: DropdownButton(
        value: widget.value,
        items: getMenuItems(),
        hint: Text(widget.hitText),
        isExpanded: true,
        underline: Container(),
        onChanged: (val){
          if(widget.onChange != null){
            widget.onChange(getItemData(val));
          }
        },
      ),
    );
  }
  
}